from django.shortcuts import render
from django.http.response import JsonResponse
# Create your views here.
from .models import User

def json(obj):
    return JsonResponse(obj,safe=False)

def get_user(request):
    try:
        return User.objects.get(id=request.session['user_id'])
    except:
        return None

def sign_in(request):
    if get_user(request):
        return json({
            'code':200,
            'detail':'success'
        })
    try:
        username=request.POST['username']
        password=request.POST['password']
    except:
        return json({
            'code':403,
            'detail':'param error'
        })
    try:
        user=User.objects.get(username=username,password=password)
        request.session['user_id']=user.id
        return json({
            'code':200,
            'detail':'success'
        })
    except:
        return json({
            'code':403,
            'detail':'password or username error'
        })
    
def sign_up(request):
    if get_user(request):
        return json({
            'code':409,
            'detail':'signed in'
        })
    print(get_user(request))
    
    username=request.POST['username']
    password=request.POST['password']
    if len(User.objects.filter(username=username,password=password)):
        return json({
            'code':409,
            'detail':'repeat'
        })
    user=User.objects.create(username=username,password=password)
    request.session['user_id']=user.id
    return json({
        'code':200,
        'detail':'success'
    })

def sign_out(request):
    if not get_user(request):
        return json({
            'code':403,
            'detail':'no sign in'
        })
    del request.session['user_id']
    return json({
        'code':200,
        'detail':'success'
    })

def user_info(request):
    user=get_user(request)
    if not user:
        return json({
            'code':403,
            'detail':'no sign in'
        })
    return json({
        'name':user.username,
        #'money':user.money, 现在虽然加入了购买系统,但决定先免费运行,避免用户知道之后要收钱
        'id':user.id
    })